package com.example.testdb;

import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

	private CommentsDataSource datasource;
	private ArrayAdapter<Comment> adapter;
	private List<Comment> values;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        datasource = new CommentsDataSource(this);
        datasource.open();

        values = datasource.getAllComments();
        adapter = new CustomArrayAdapter(this, values);
        
        ListView mainListView = (ListView) findViewById(R.id.mainListView);
		mainListView.setAdapter(adapter);
		
		Button createButton = (Button)findViewById(R.id.create);
		createButton.setOnClickListener(createListener);
		registerForContextMenu(mainListView);
    }

    @Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		if (v.getId() == R.id.mainListView) {
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
			menu.setHeaderTitle(Long.toString(values.get(info.position).getId()));
			String[] menuItems = getResources().getStringArray(R.array.menu);
			for (int i = 0; i < menuItems.length; i++) {
				menu.add(Menu.NONE, i, i, menuItems[i]);
			}
		}
	}
    
    @Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		
		Comment comment = (Comment) adapter.getItem(info.position);
        datasource.deleteComment(comment);
        values.remove(comment);
        adapter.notifyDataSetChanged();
		
		return true;
	}
    
    @Override
    protected void onResume() {
      datasource.open();
      super.onResume();
    }

    @Override
    protected void onPause() {
      datasource.close();
      super.onPause();
    }
    
    private OnClickListener createListener = new OnClickListener() {
		
		public void onClick(View v) {
			Comment comment = null;
			EditText text = (EditText) findViewById(R.id.comment);
			comment = datasource.createComment(text.getText().toString());
			values.add(comment);
			adapter.notifyDataSetChanged();
		    //adapter.add(comment);
		}
	};
    
}
